package cn.edu.njtc.service.impl;

import cn.edu.njtc.common.ErrorMessage;
import cn.edu.njtc.entity.dto.ActivityCreateDto;
import cn.edu.njtc.entity.dto.ActivityQueryDto;
import cn.edu.njtc.entity.dto.ActivityUpdateDto;
import cn.edu.njtc.entity.pojo.EducationActivity;
import cn.edu.njtc.exception.BizException;
import cn.edu.njtc.mapper.EducationActivityMapper;
import cn.edu.njtc.service.EducationActivityService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class EducationActivityServiceImpl implements EducationActivityService {
    private final EducationActivityMapper activityMapper;


    @Override
    public List<EducationActivity> listActivities() {
        return activityMapper.selectAllActivities();
    }

    @Override
    public EducationActivity getActivityById(Long activityId) {
        return activityMapper.selectById(activityId);
    }

    @Override
    @Transactional
    public Long createActivity(ActivityCreateDto createDTO) {
        EducationActivity activity = new EducationActivity();
        BeanUtils.copyProperties(createDTO, activity);
        activity.setStatus("未开始");
        activity.setCreated(LocalDateTime.now());
        activityMapper.insert(activity);
        return activity.getActivityId();
    }

    @Override
    @Transactional
    public void updateActivity(ActivityUpdateDto updateDTO) throws BizException {
        EducationActivity activity = activityMapper.selectById(updateDTO.getActivityId());
        if (activity == null) {
            throw new BizException(ErrorMessage.ACTIVITY_NOT_FOUND);
        }

        if ("已取消".equals(activity.getStatus()) || "已结束".equals(activity.getStatus())) {
            throw new BizException(ErrorMessage.ACTIVITY_CANCELED);
        }

        BeanUtils.copyProperties(updateDTO, activity);
        activityMapper.updateById(activity);
    }

    @Override
    @Transactional
    public void cancelActivity(Long activityId, String cancelReason) throws BizException {
        EducationActivity activity = activityMapper.selectById(activityId);
        if (activity == null) {
            throw new BizException(ErrorMessage.ACTIVITY_NOT_FOUND);
        }

        if ("已取消".equals(activity.getStatus())) {
            throw new BizException(ErrorMessage.ACTIVITY_CANCELED);
        }



        activity.setStatus("已取消");
        activityMapper.updateById(activity);
    }


}